package giit.computerbase.server;

import giit.computerbase.dao.SQL;
import giit.computerbase.dao.SQLFactory;
import giit.computerbase.util.Application;
import giit.computerbase.util.BrowserAnalysis;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * User: tum0r
 * Package Name: giit.computerbase.server
 * Time: 2018/11/11 Sunday 09:22:06
 */
public class HistoryServer {
    private SQL sql;

    public HistoryServer() {
        try {
            sql = SQLFactory.getSQL();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void record(String ip, String ua, String organization, String userType, String userName, String operation, String state) {
        sql.open((String) Application.getConfig().databaseConfig.get("address"),
                (int) Application.getConfig().databaseConfig.get("port"),
                Application.DATABASE_NAME,
                (String) Application.getConfig().databaseConfig.get("encode"),
                (String) Application.getConfig().databaseConfig.get("user"),
                (String) Application.getConfig().databaseConfig.get("password"));
        HashMap<String, String> userAgent = BrowserAnalysis.analysis(ua);
        String device = userAgent.get("device");
        String os = userAgent.get("os");
        String browser = userAgent.get("browser");
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss (z X)");
        String time = timeFormat.format(new Date());
        sql.add("insert into history value(?,?,?,?,?,?,?,?,?,?)", new Object[]{ip, device, os, browser, organization, userType, userName, operation, state, time});
        try {
            sql.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
